package softtech.apps.callblocker;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import softtech.apps.utility.FileUtility;
import softtech.apps.callblocker.R;
import softtech.apps.callblocker.adapter.AdapterCallHistoryInformation;
import softtech.apps.callblocker.model.BlackListItem;
import softtech.apps.callblocker.model.CallBlockedItem;
import softtech.apps.callblocker.model.DatabaseHanler;
import softtech.apps.callblocker.model.SectionStructure;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.provider.LiveFolders;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class ActivityCallHistoryInformation extends Activity{
	
	LayoutInflater inf;
	AdapterCallHistoryInformation adapterInfo;
	ArrayList<SectionStructure> alsectionStructure = new ArrayList<SectionStructure>();
	//List call
	ArrayList<CallBlockedItem> listcallblock = new ArrayList<CallBlockedItem>();
	//get Phonenumber
	String PhoneNumber;
	
	/**
	 * get extra date
	 */
	String DateCall;
	/**
	 * get mode call
	 */
	String modecall;
	int mode;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setTitle("Information");
		setContentView(R.layout.item_call_history_information);
		//get recent call
		getRecentCall(getApplicationContext());
		/**
		 * set Adapter listview
		 */
		ListView lvinfo = (ListView) findViewById(R.id.listviewCallhistory);
		inf = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
		adapterInfo = new AdapterCallHistoryInformation(listcallblock,inf,getApplicationContext());
		lvinfo.setAdapter(adapterInfo);
		/**
		 * create component
		 */
		//Flipper view
		final Button btCallInfo = (Button) findViewById(R.id.btCallInfoHistory);
		final Button btMessengerInfo = (Button) findViewById(R.id.btMessengerInfoHistory);
		/**
		 * Save to contact
		 */
	  Button btSaveToContact = (Button) findViewById(R.id.btInfoHistorySaveToContact);
			  btSaveToContact.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					fSaveToContact("Name",PhoneNumber);
				}
			});
			/**
			 * save to exception list  
			 */
		Button btSaveToExceptionList = (Button) findViewById(R.id.btInfoHistorySaveToExceptionList);
		btSaveToExceptionList.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				DatabaseHanler db = new DatabaseHanler(ActivityCallHistoryInformation.this);
				String name= null;
				Cursor cphone = ActivityCallHistoryInformation.this.getContentResolver().query(
						ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
						Phone.NUMBER + "=?", new String[] {PhoneNumber }, null);
				if(cphone!=null ){
					while(cphone.moveToNext()){
				name = cphone.getString(cphone
						.getColumnIndex(Phone.DISPLAY_NAME));
				break;
					}
				}else{
					name = "Unknown";
				}
				BlackListItem blackListItem = new BlackListItem(PhoneNumber, name,
					      0);
					    db.insertBlackListItem(blackListItem);
					    Toast.makeText(getApplicationContext(), "Saved to Exception list", Toast.LENGTH_LONG).show();
			}
		});
		/**
		 *  call info
		 */
		btCallInfo.setText("CALL ("+listcallblock.size()+")");
		btCallInfo.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				fCallInfo(btCallInfo, btMessengerInfo);
				fRecall(PhoneNumber);
			}
		});
		/**
		 * Messenger info
		 */
		btMessengerInfo.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				fMessengerInfo(btCallInfo, btMessengerInfo);
			}
		});
		/**
		 * back history
		 */
		
		
	}
	 @Override
		public boolean onOptionsItemSelected(MenuItem item) {

			switch (item.getItemId()) {
			case android.R.id.home:
				
					Intent inHistory = new Intent(ActivityCallHistoryInformation.this,
							ActivityCallHistory.class);
					startActivity(inHistory);
					finish();
				

				break;
			default:
				break;
			}

			return super.onOptionsItemSelected(item);
		}
	/**
	 * Save to contact
	 * 
	 */
	private void fSaveToContact( String Name,String PhoneNumber){
		Intent intent = new Intent(Intent.ACTION_INSERT, 
                ContactsContract.Contacts.CONTENT_URI);
		intent.putExtra(ContactsContract.Intents.Insert.NAME, Name);
		intent.putExtra(ContactsContract.Intents.Insert.PHONE, PhoneNumber);
		startActivity(intent);
	}
	/**
	 * get all recent call history
	 * 
	 */
	private void  getRecentCall(Context context){
		Intent intent = getIntent();
		PhoneNumber  = intent.getStringExtra("phonenumber");
		Log.v("date: ",""+ PhoneNumber);
		DateCall = intent.getStringExtra("datetime");
		DatabaseHanler dbhblockcall = new DatabaseHanler(context);
		listcallblock = new ArrayList<CallBlockedItem>();
		listcallblock = (ArrayList<CallBlockedItem>) dbhblockcall
				.getCallBlockItem(null,
						CallBlockedItem.PHONE_NUMBER +" =? and " +CallBlockedItem.DATE_TIME
						+" LIKE ?", new String[]{PhoneNumber,"%"+stringToDate(DateCall)+"%"}, null, null);
//		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
//		String date1 = df.format(gettime);
//		DateCall = date1;

	}
	/**
	 * infomation call history
	 * @param btCallInfo
	 * @param btMessengerInfo
	 * @param vfInfoHistory
	 */
	private void  fCallInfo(final Button btCallInfo , final Button btMessengerInfo){
		btCallInfo.setBackgroundResource(R.drawable.frame_press);
		btCallInfo.setTextColor(Color.parseColor("#3a3d47"));
		btMessengerInfo.setBackgroundResource(R.drawable.frame);
		btMessengerInfo.setTextColor(Color.WHITE);
	}
	/**
	 * infomation messenger history
	 * @param btCallInfo
	 * @param btMessengerInfo
	 * @param vfInfoHistory
	 */
	private void  fMessengerInfo(final Button btCallInfo , final Button btMessengerInfo){
		btCallInfo.setBackgroundResource(R.drawable.frame);
		btCallInfo.setTextColor(Color.WHITE);
		btMessengerInfo.setBackgroundResource(R.drawable.frame_press);
		btMessengerInfo.setTextColor(Color.parseColor("#3a3d47"));
		
		Intent i = new Intent(ActivityCallHistoryInformation.this,ActivityChat.class);
		i.putExtra("phonenumber", PhoneNumber);
		i.putExtra("setintent", 1);
		startActivity(i);
		finish();
	}
	/**
	 * Recall
	 * @param phonenumber
	 */
	private void fRecall(String phonenumber){
		Intent callIntent = new Intent(Intent.ACTION_CALL);
		callIntent.setData(Uri.parse("tel:"+phonenumber));
		startActivity(callIntent);
	}
	/**
	 * convert datetime to date
	 * @param date
	 */
	private String stringToDate(String day){
		if(!FileUtility.checkStringNotNull(day)){
			return "";
		}
		Log.e(" vkl chym se " , " ngay ="+day);
		Date date = new Date();
		SimpleDateFormat  format = new SimpleDateFormat("yyyy-MM-dd HH:mm");  
		try {  
		     date = format.parse(day);  
		    System.out.println(date);  
		} catch (ParseException e) {  
		    // TODO Auto-generated catch block  
		    e.printStackTrace();  
		}
		SimpleDateFormat  dateformat = new SimpleDateFormat("yyyy-MM-dd");  
		String day1=null;
		try {  
		  
		 day1= dateformat.format(date);
		} catch (Exception e) {  
		    // TODO Auto-generated catch block  
		    e.printStackTrace();  
		}
		return day1;
	}
	/**
	 * convert datetime to time
	 * @param time
	 * @return
	 */
	private String stringToTime(String time){
		Date date = null;
		SimpleDateFormat  format = new SimpleDateFormat("yyyy-MM-dd HH:mm");  
		try {  
		     date = format.parse(time);  
		    System.out.println(date);  
		} catch (ParseException e) {  
		    // TODO Auto-generated catch block  
		    e.printStackTrace();  
		}
		SimpleDateFormat  dateformat = new SimpleDateFormat("HH:mm");  
		String time1 =null;
		try {  
		  
		 time1= dateformat.format(date);
		} catch (Exception e) {  
		    // TODO Auto-generated catch block  
		    e.printStackTrace();  
		}
		return time1;
	}

	 
	 
	 

}
